﻿using System.Windows;
using Airborne.ScrumPoker.Module.Events;
using Microsoft.Practices.Composite.Events;
using Microsoft.Practices.Composite.Wpf.Events;

namespace Airborne.ScrumPoker.Presentation.Client
{
    /// <summary>
    /// Interaction logic for Shell.xaml
    /// </summary>
    public partial class Shell : Window
    {
        private IEventAggregator EventAggregator { get; set; }

        public Shell(IEventAggregator eventAggregator)
        {
            EventAggregator = eventAggregator;
            InitializeComponent();
            SubscribeToEvents();
            this.Closing += new System.ComponentModel.CancelEventHandler(ShellClosing);
        }

        private void SubscribeToEvents()
        {
            EventAggregator.GetEvent<GenericEvent<string>>().Subscribe(ShowErrorMessage, ThreadOption.UIThread, true, p => p.Topic == EventTopics.Error);
            EventAggregator.GetEvent<GenericEvent<int>>().Subscribe(CloseShell, ThreadOption.UIThread, true, p => p.Topic == EventTopics.Kill);
        }


        private void ShowErrorMessage(EventParameters<string> parameters)
        {
            if (!string.IsNullOrEmpty(parameters.Value))
            {
                MessageBox.Show(this, parameters.Value, Application.Current.MainWindow.Title,MessageBoxButton.OK, MessageBoxImage.Error, MessageBoxResult.OK, MessageBoxOptions.None);
            }
        }


        private void ShellClosing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            EventAggregator.GetEvent<GenericEvent<int>>().Publish(new EventParameters<int>(EventTopics.ApplicationShutdown, 0));
        }


        private void CloseShell(EventParameters<int> parameters)
        {
            this.Close();
        }
    }
}
